package com.usp.cloudendpoint_cient;

import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.json.gson.GsonFactory;
import com.usp.cloudendpoint.messagepojoendpoint.Messagepojoendpoint;
import com.usp.cloudendpoint.messagepojoendpoint.model.MessagePojo;

public class MainActivity extends Activity {

	ProgressDialog dialog;
	TextView txtMessage;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.query_cloudendpoint) {
			queryCloudEndpoint();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void queryCloudEndpoint() {

		AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {

			@Override
			public void onPreExecute() {
				txtMessage = (TextView) findViewById(R.id.result_text);
				txtMessage.setText("Connecting....");
				dialog = ProgressDialog.show(MainActivity.this,
						null /* title */,
						"Please wait...");
			}

			@Override
			protected String doInBackground(Void... params) {
				Messagepojoendpoint.Builder builder =new Messagepojoendpoint.Builder(
						AndroidHttp.newCompatibleTransport(),
						new GsonFactory(),
						null /* httpRequestInitializer */);
				try {
					MessagePojo pojo = builder.build().getMessagePojo().execute();
					return pojo.getMessage();
				} catch (IOException e) {
					Log.e("error:", e.toString());
					return e.toString();
				}
			}

			@Override
			public void onPostExecute(String message) {
				txtMessage.setText("Result:  " + message);
				dialog.dismiss();
				Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
			}
		};
		task.execute();
	}
}
